﻿using System;
using System.Linq;
using System.Linq.Expressions;

namespace Mvc.XForms.Controls {
	public class XFormContext<TParentContext, TContext> : XFormContextBase<TParentContext, TContext>, IContext<TContext> {
		public override XFormControlType ControlType {
			get { return XFormControlType.Context; }
		}

		public XFormContext(IContainerControl<TParentContext> parent, Expression<Func<TParentContext, TContext>> bind)
			: base(parent, bind.Body) {
			ModelContext = bind.Compile()(parent.ModelContext);
			if (ModelContext == null)
				ModelContext = Activator.CreateInstance<TContext>();
		}

		public override void Render() {
			throw new NotImplementedException();
		}

		public override object ToJson() {
			if (IsInRepeatTemplate) {
				var json = new {
					id = ID,
					type = (int)ControlType,
					acts = Actions.Select(act => act.ToJson()),
					cons = Controls.Select(con => con.ToJson()).Where(obj => obj != null)
				};
				return json;
			}

			return null;
		}
	}
}